<template>
  <div class="wrapper">
    <!-- <div :split="false" class="lists">
      <a-alert :show-icon="false" message="1、可以生成带参数的二维码名片，支持活码功能，即随机选取设置的活码成员推给用户。加企业微信为好友后，可以给微信联系人自动回复相应欢迎消息和打标签。" banner />
      <a-alert :show-icon="false" message="2、每创建一个渠道活码，该码则自动进入【内容引擎】--【图片类型】--分组【渠道码-企业微信】，以素材的方式通过聊天侧边栏快速发送给客户。" banner />
      <a-alert :show-icon="false" message="3、受限于官方，单人类型的渠道码创建后尽量不要再修改成员，否则会造成列表中，该二维码中间的头像与配置的成员头像不一致，但是并不影响功能使用。" banner />
      <a-alert :show-icon="false" message="4、如果企业在企业微信后台为相关成员配置了可用的欢迎语，使用第三方系统配置欢迎语，则均不起效，推送的还是企业微信官方的。" banner />
    </div> -->
    <a-card>
      <a-form :label-col="{ span: 7 }" :wrapper-col="{ span: 14 }">
        <a-row :gutter="16">
          <a-col :lg="8">
            <a-form-item
              label="名称：">
              <a-input v-model="screentData.name" placeholder="搜索渠道分佣码名称"></a-input>
            </a-form-item>
          </a-col>
          <a-col :lg="8">
            <a-form-item
              label="渠道分佣码类型：">
              <a-select v-model="screentData.type">
                <a-select-option v-for="item in typeList" :key="item.value">
                  {{ item.label }}
                </a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :lg="8">
            <a-form-item
              label="分组：">
              <a-select v-model="screentData.groupId">
                <a-select-option v-for="item in groupList" :key="item.groupId">
                  {{ item.name }}
                </a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
        </a-row>
      </a-form>
      <div class="search">
        <a-button v-permission="'/channelCode/index@search'" type="text" style="marginRight: 10px" @click="getTableData">查询</a-button>
        <a-button @click="() => {this.screentData = {}}">重置</a-button>
      </div>
      <div class="btn-box">
        <router-link :to="{path: '/channelCode/store'}">
          <a-button v-permission="'/channelCode/store'" type="primary">新建渠道分佣码</a-button>
        </router-link>
        <a-button type="primary">
          <a :href="qrcodeUrl" download>批量下载渠道分佣码</a>
        </a-button>
        <a-button v-permission="'/channelCode/index@editGroup'" type="text" @click="() => {this.editGroupDis = true}">修改分组</a-button>
        <a-button v-permission="'/channelCode/index@add'" type="text" @click="() => {this.addGroupDis = true}">新建分组</a-button>
      </div>
      <a-table
        style="marginTop: 20px"
        bordered
        :columns="columns"
        :data-source="tableData"
        :rowKey="record => record.channelCodeId"
        :row-selection="{ selectedRowKeys: deleteList, onChange: onSelectChange }"
        :pagination="pagination"
        @change="handleTableChange">
        <div slot="image" slot-scope="text, record" class="img-box">
          <img style="width:90px; height:auto;" :src="record.qrcodeUrl" alt="">
          <span>{{ record.type }}</span>
        </div>
        <div slot="tags" slot-scope="text, record">
          <div v-if="record.tags.length !== 0" v-for="(item, index) in record.tags" :key="index + 'lseg'">{{ item }}</div>
        </div>
        <div slot="action" slot-scope="text, record">
          <template>
            <router-link :to="{path:`/channelCode/store?channelCodeId=${record.channelCodeId}`}">
              <a-button v-permission="'/channelCode/index@edit'" type="link">编辑</a-button>
            </router-link>
            <!-- <a-button type="link">编辑</a-button> -->
            <a-button v-permission="'/channelCode/index@customer'" type="link" @click="getChannelCodeContact(record.channelCodeId)">客户</a-button>
            <a-button v-permission="'/channelCode/index@download'" type="link">
              <a :href="record.qrcodeUrl" download>下载</a>
            </a-button>
            <a-button v-permission="'/channelCode/index@move'" type="link" @click="moveGroup(record.channelCodeId, record.groupId)">移动</a-button>
            <router-link :to="{path: `/channelCode/statistics?channelCodeId=${record.channelCodeId}`}">
              <a-button v-permission="'/channelCode/statistics'" type="link">统计</a-button>
            </router-link>
            <a-button type="link" @click="getChannelBusinessInfo(record.channelCodeId)">编辑渠道商名称及手机号</a-button>
          </template>
        </div>
        <div slot="brokerageScale" slot-scope="text, record">
          <span>{{ record.brokerageScale }}% </span>
        </div>
      </a-table>
    </a-card>
    <a-modal
      width="800px"
      title="扫码客户"
      :visible="contactModal"
      @cancel="() => {this.contactModal = false; this.contactPagination.current = 1;}">
      <a-table
        style="marginTop: 20px;"
        bordered
        :columns="contactColumns"
        :data-source="contactTableData"
        :rowKey="record => record.contactId"
        :pagination="contactPagination"
        @change="handleTableChangeContact">
        <span slot="createOrder" slot-scope="record">
          <a @click="showOrderWindow(record.contactId)">生成订单</a>
        </span>
        <span slot="viewOrder" slot-scope="record">
          <a @click="getOrderInfo(record.contactId)">查看订单</a>
        </span>
      </a-table>
      <template slot="footer">
        <a-button type="primary" @click="() => {this.contactModal = false; this.contactPagination.current = 1;}">确定</a-button>
      </template>
    </a-modal>
    <a-modal
      title="渠道商信息"
      :visible="channelBusinessModal"
      @cancel="() => {this.channelBusinessModal = false; this.channelBusinessData = {}}">
      <a-form-model :label-col="{ span: 6 }" :wrapper-col="{ span: 14}" :model="channelBusinessData">
        <a-form-model-item label="渠道商名称：" prop="channelBusinessName">
          <a-input v-model="channelBusinessData.channelBusinessName"/>
        </a-form-model-item>
        <a-form-model-item label="渠道商手机号：" prop="channelBusinessPhone">
          <a-input v-model="channelBusinessData.channelBusinessPhone" :max-length="11" type="number"/>
        </a-form-model-item>
      </a-form-model>
      <template slot="footer">
        <a-button @click="() => {this.channelBusinessModal = false; this.channelBusinessData = {}}">取消</a-button>
        <a-button type="primary" :loading="btnLoading" @click="editChannelBusinessInfo()">确定</a-button>
      </template>
    </a-modal>
    <a-modal
      title="生成订单"
      :visible="createOrderDis"
      @cancel="() => {this.createOrderDis = false; this.createOrderData = {}}">
      <a-form-model :label-col="{ span: 6 }" :wrapper-col="{ span: 14}" :rules="createOrderRules" :model="createOrderData" ref="createOrderRules">
        <a-form-model-item label="订单描述：" prop="orderDesc">
          <a-input v-model="createOrderData.orderDesc" placeholder="格式如：充值中心-QQ会员充值"/>
        </a-form-model-item>
        <a-form-model-item label="支付金额：" prop="total_fee">
          <a-input v-model="createOrderData.total_fee"/>
        </a-form-model-item>
      </a-form-model>
      <template slot="footer">
        <a-button @click="() => {this.createOrderDis = false; this.createOrderData = {}}">取消</a-button>
        <a-button type="primary" :loading="btnLoading" @click="createOrder">确定</a-button>
      </template>
    </a-modal>
    <a-modal
      width="600px"
      title="客户订单详情"
      :visible="personalOrderDis"
      @cancel="() => {this.personalOrderDis = false;}">
      <a-table
        style="marginTop: 20px;"
        bordered
        :columns="personalOrderColumns"
        :data-source="personalOrderData"
        :rowKey="record => record.outTradeNo"
        :pagination="contactPagination"
        @change="handleTableChangePersonalOrder">
      </a-table>
      <template slot="footer">
        <a-button type="primary" @click="() => {this.personalOrderDis = false;}">确定</a-button>
      </template>
    </a-modal>
    <a-modal
      title="付款码"
      :visible="codeUrlDis"
      @cancel="() => {this.codeUrlDis = false;}">
      <div align="center">
        <img :src="codeUrl"/>
      </div>
      <template slot="footer">
        <a-button @click="() => {this.codeUrlDis = false;}">请复制付款码后再退出</a-button>
      </template>
    </a-modal>
    <a-modal
      title="新建分组"
      :visible="addGroupDis"
      @cancel="() => {this.addGroupDis = false; this.groupName = ''}">
      <a-form-model :label-col="{ span: 6 }" :wrapper-col="{ span: 14}">
        <a-form-model-item label="分组名称：">
          <p>每个分组名称最多15个字。同时新建多个分组时，请用“空格”隔开</p>
          <a-input v-model="groupName"/>
        </a-form-model-item>
      </a-form-model>
      <template slot="footer">
        <a-button @click="() => {this.addGroupDis = false; this.groupName = ''}">取消</a-button>
        <a-button type="primary" :loading="btnLoading" @click="addGroup">确定</a-button>
      </template>
    </a-modal>
    <a-modal
      title="修改分组"
      :visible="editGroupDis"
      @cancel="() => {this.editGroupDis = false; this.editGroupData = {}}">
      <a-form-model :label-col="{ span: 6 }" :wrapper-col="{ span:14}">
        <a-form-model-item label="选择分组：">
          <a-select v-model="editGroupData.groupId">
            <a-select-option v-for="item in groupList" :key="item.groupId">
              {{ item.name }}
            </a-select-option>
          </a-select>
        </a-form-model-item>
        <a-form-model-item label="修改分组名称：">
          <a-input v-model="editGroupData.name"/>
        </a-form-model-item>
      </a-form-model>
      <template slot="footer">
        <a-button @click="() => {this.editGroupDis = false; this.editGroupData = {}}">取消</a-button>
        <a-button type="primary" :loading="btnLoading" @click="editGroup">确定</a-button>
      </template>
    </a-modal>
    <div class="mbox" ref="mbox"></div>
    <a-modal
      :getContainer="() => $refs.mbox"
      title="移动分组"
      class="move-box"
      :visible="moveGroupDis"
      @cancel="() => {this.moveGroupDis = false}">
      <div class="group-box">
        <div :class="moveGroupId == item.groupId ? 'active' : ''" v-for="item in groupList" :key="item.groupId" @click="changeGroup(item.groupId)">
          {{ item.name }}
        </div>
      </div>
      <template slot="footer">
        <a-button @click="() => {this.moveGroupDis = false; this.moveGroupData = {}}">取消</a-button>
        <a-button type="primary" @click="moveGroupDefined">确定</a-button>
      </template>
    </a-modal>
  </div>
</template>

<script>
import { channelCodeList, channelCodeGroup, channelCodeGroupAdd, channelCodeGroupUpdate, channelCodeContact, channelCodeGroupMove, wxpayUnifiedOrder, getOrderInfoByUserId, channelCodeDetail, editChannelBusiness } from '@/api/channelCode'
export default {
  data () {
    return {
      personalOrderDis: false,
      contactId: '',
      channelCodeId: '',
      deleteModal: false,
      createOrderDis: false,
      codeUrlDis: false,
      editGroupDis: false,
      addGroupDis: false,
      visible: false,
      btnLoading: false,
      contactModal: false,
      channelBusinessModal: false,
      moveGroupDis: false,
      deleteList: [],
      columns: [
        {
          align: 'center',
          title: '渠道分佣码',
          dataIndex: 'image',
          scopedSlots: { customRender: 'image' }
        },
        {
          align: 'center',
          title: '分佣码名称',
          dataIndex: 'name'
        },
        {
          align: 'center',
          title: '分组',
          dataIndex: 'groupName'
        },
        {
          align: 'center',
          title: '客户数',
          dataIndex: 'contactNum'
        },
        {
          align: 'center',
          title: '标签',
          dataIndex: 'tags',
          scopedSlots: { customRender: 'tags' }
        },
        {
          align: 'center',
          title: '自动添加好友',
          dataIndex: 'autoAddFriend'
        },
        {
          align: 'center',
          title: '渠道返佣比例',
          dataIndex: 'brokerageScale',
          scopedSlots: { customRender: 'brokerageScale' }
        },
        {
          align: 'center',
          title: '渠道商名称',
          dataIndex: 'channelBusinessName'
        },
        {
          align: 'center',
          title: '渠道商手机号',
          dataIndex: 'channelBusinessPhone'
        },
        {
          align: 'center',
          title: '佣金总额/元',
          dataIndex: 'brokerage'
        },
        {
          align: 'center',
          title: '操作',
          width: '250px',
          dataIndex: 'action',
          scopedSlots: { customRender: 'action' }
        }
      ],
      tableData: [],
      pagination: {
        total: 0,
        current: 1,
        pageSize: 10,
        showSizeChanger: true
      },
      screentData: {},
      groupList: [],
      typeList: [
        {
          label: '全部',
          value: 0
        },
        {
          label: '单人',
          value: 1
        },
        {
          label: '多人',
          value: 2
        }
      ],
      // 客户订单数据
      personalOrderData: [],
      personalOrderColumns: [
        {
          align: 'center',
          key: 'orderDesc',
          title: '订单描述',
          dataIndex: 'orderDesc'
        },
        {
          align: 'center',
          key: 'outTradeNo',
          title: '订单编号',
          dataIndex: 'outTradeNo'
        },
        {
          align: 'center',
          key: 'totalFee',
          title: '订单金额',
          dataIndex: 'totalFee'
        },
        {
          align: 'center',
          key: 'status',
          title: '支付状态',
          dataIndex: 'status',
          customRender: function (text){
            if (text == '1') {
              return '已支付'
            } else {
              return '未支付'
            }
          }
        },
        {
          align: 'center',
          key: 'createdAt',
          title: '创建时间',
          dataIndex: 'createdAt',
          customRender: function (text){
            var date = new Date(text)
            var Y = date.getFullYear() + '/'
            var M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) + '/'
            var D = (date.getDate() < 10 ? '0' + (date.getDate()) : date.getDate()) + ' '
            var h = (date.getHours() < 10 ? '0' + (date.getHours()) : date.getHours()) + ':'
            var m = (date.getMinutes() < 10 ? '0' + (date.getMinutes()) : date.getMinutes()) + ':'
            var s = (date.getSeconds() < 10 ? '0' + (date.getSeconds()) : date.getSeconds())
            return Y + M + D + h + m + s
          }
        }
      ],
      // 客户数据
      contactTableData: [],
      // 渠道商数据
      channelTableData: [],
      contactColumns: [
        {
          align: 'center',
          title: '客户名称',
          dataIndex: 'name',
          key: 'name'
        },
        {
          align: 'center',
          title: '归属成员',
          dataIndex: 'employees',
          key: 'employees'
        },
        {
          align: 'center',
          title: '添加时间',
          dataIndex: 'createTime',
          key: 'createTime'
        },
        {
          title: '生成订单',
          key: 'createOrder',
          width: '30%',
          scopedSlots: { customRender: 'createOrder' },
          align: 'center'
        },
        {
          title: '查看订单',
          key: 'viewOrder',
          width: '30%',
          scopedSlots: { customRender: 'viewOrder' },
          align: 'center'
        }
      ],
      contactPagination: {
        total: 0,
        current: 1,
        pageSize: 10,
        showSizeChanger: true
      },
      // 生成订单
      createOrderData: {},
      // 点击编辑渠道商反显数据
      channelBusinessData: {},
      // 微信订单二维码
      codeUrl: '',
      // 分组
      groupName: '',
      editGroupData: {},
      // 移动分组
      moveGroupId: '',
      qrcodeUrl:'#',
      // channelCodeId: ''
      // 生成订单表单规则
      createOrderRules: {
        orderDesc: [{ required: true, message: '请填写订单描述', trigger: 'blur' }],
        total_fee: [{ required: true, message: '请填写支付金额', trigger: 'blur' }]
      }
    }
  },
  created () {
    this.getTableData()
    this.getGroupList()
  },
  methods: {
    // 数据筛选
    onSelectChange (val) {
      this.deleteList = val
      if (this.deleteList.length > 0) {
        const tagIds = this.deleteList.join(',')
        const fPath = process.env.VUE_APP_API_BASE_URL + '/channelCode/download?downloadIds=' + tagIds
        this.qrcodeUrl = fPath
      } else {
        this.qrcodeUrl = '#'
      }
      console.log(this.qrcodeUrl)
    },
    getTableData () {
      const params = {
        name: this.screentData.name,
        groupId: this.screentData.groupId,
        type: this.screentData.type,
        page: this.pagination.current,
        perPage: this.pagination.pageSize
      }
      channelCodeList(params).then(res => {
        this.tableData = res.data.list
        this.pagination.total = res.data.page.total
      })
    },
    handleTableChange ({ current, pageSize }) {
      this.pagination.current = current
      this.pagination.pageSize = pageSize
      this.getTableData()
    },
    handleTableChangeContact ({ current, pageSize }) {
      this.contactPagination.current = current
      this.contactPagination.pageSize = pageSize
      this.getChannelCodeContact(this.channelCodeId)
    },
    // 个人订单详情
    handleTableChangePersonalOrder ({ current, pageSize }) {
      this.contactPagination.current = current
      this.contactPagination.pageSize = pageSize
      this.getOrderInfo()
    },
    // 个人订单详情
    getOrderInfo (id) {
      this.contactId = id
      getOrderInfoByUserId({
        contactId: this.contactId,
        page: this.contactPagination.current,
        perPage: this.contactPagination.pageSize
      }).then(res => {
        this.personalOrderDis = true
        this.personalOrderData = res.data.list
        this.contactPagination.total = res.data.page.total
      })
    },
    getGroupList () {
      channelCodeGroup().then(res => {
        this.groupList = res.data
      })
    },
    // 获取客户
    getChannelCodeContact (id) {
      this.channelCodeId = id
      channelCodeContact({
        channelCodeId: this.channelCodeId,
        page: this.contactPagination.current,
        perPage: this.contactPagination.pageSize
      }).then(res => {
        this.contactModal = true
        this.contactTableData = res.data.list
        this.contactPagination.total = res.data.page.total
      })
    },
    // 获取渠道商信息
    getChannelBusinessInfo (id) {
      this.channelCodeId = id
      channelCodeDetail({
        channelCodeId: this.channelCodeId
      }).then(res => {
        this.channelBusinessModal = true
        this.channelBusinessData = res.data.baseInfo
      })
    },
    // 新增分组
    addGroup () {
      const reg = /\s+/g
      const name = this.groupName.replace(reg, ' ').split(' ')
      let falg = false
      let flag = false
      let fg = false
      if (name.length > 1) {
        const lengths = Array.from(new Set(name)).length
        if (lengths < name.length) {
          flag = true
        }
      }
      name.map((item, index) => {
        if (item == '') {
          fg = true
        }
        if (item.length > 15) {
          this.$message.error('每个敏感词最多15个字')
          falg = true
        }
      })
      if (falg) {
        return
      }
      if (fg) {
        this.$message.error('请输入正确的分组名称')
        return
      }
      if (flag) {
        this.$message.error('分组名称重复')
        return
      }
      this.btnLoading = true
      channelCodeGroupAdd({
        name: name
      }).then(res => {
        this.getGroupList()
        this.addGroupDis = false
        this.groupName = ''
        this.btnLoading = false
      }).catch(res => {
        this.btnLoading = false
      })
    },
    // 点击确定生成订单
    createOrder () {
      this.$refs.createOrderRules.validate(valid => {
        if (valid) {
          this.btnLoading = true
          wxpayUnifiedOrder({
            order_desc: this.createOrderData.orderDesc,
            total_fee: this.createOrderData.total_fee,
            product_id: this.createOrderData.product_id,
            contact_id: this.contactId,
            channel_code_id: this.channelCodeId
          }).then(res => {
            // console.log(JSON.stringify(res))
            this.codeUrl = 'data:image/jpg;base64,' + res.code_url
            this.codeUrlDis = true
            this.createOrderDis = false
            this.createOrderData = {}
            this.btnLoading = false
          }).catch(res => {
            this.btnLoading = false
          })
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    // 点击确定，编辑渠道商信息
    editChannelBusinessInfo () {
      this.btnLoading = true
      editChannelBusiness({
        channelBusinessName: this.channelBusinessData.channelBusinessName,
        channelBusinessPhone: this.channelBusinessData.channelBusinessPhone,
        channelCodeId: this.channelCodeId
      }).then(res => {
        this.channelBusinessModal = false
        this.channelBusinessData = {}
        this.btnLoading = false
        this.getTableData()
      }).catch(res => {
        this.btnLoading = false
      })
    },
    // 查看订单详情
    personalOrderInfo (contactId) {
      this.personalOrderDis = true
    },
    // 展示生成订单弹窗
    showOrderWindow (contactId) {
      this.createOrderDis = true
      this.contactId = contactId
    },
    // 修改分组
    editGroup () {
      const reg = /\s+/g
      const name = this.editGroupData.name
      if (this.editGroupData.groupId == undefined) {
        this.$message.error('请选择分组')
        return
      }
      if (reg.test(name)) {
        this.$message.error('请输入正确的分组名称')
        return
      }
      this.btnLoading = true
      channelCodeGroupUpdate({
        groupId: this.editGroupData.groupId,
        name: this.editGroupData.name
      }).then(res => {
        this.editGroupData = {}
        this.getGroupList()
        this.editGroupDis = false
        this.btnLoading = false
      }).catch(res => {
        this.btnLoading = false
      })
    },
    // 移动分组
    moveGroup (id, groupId) {
      this.moveGroupDis = true
      this.channelCodeId = id
      this.moveGroupId = groupId
    },
    // 选择移动分组
    changeGroup (id) {
      this.moveGroupId = id
    },
    // 确定移动分组
    moveGroupDefined () {
      channelCodeGroupMove({
        channelCodeId: this.channelCodeId,
        groupId: this.moveGroupId
      }).then(res => {
        this.moveGroupDis = false
        this.moveGroupId = ''
        this.channelCodeId = ''
        this.getTableData()
      })
    }
  }
}
</script>

<style lang="less" scoped>
  .wrapper{
    .search {
      display: flex;
      justify-content: flex-end;
    }
    .btn-box {
      margin-top: 20px;
      display: flex;
      justify-content: flex-end;
      .ant-btn {
        margin-left: 10px;
      }
    }
    .img-box {
      display: flex;
      flex-direction: column;
      align-items: center
    }
    .mbox {
      .move-box {
        .group-box {
          display: flex;
          flex-wrap: wrap;
          div {
            padding: 0 10px;
            height: 40px;
            line-height: 40px;
            text-align: center;
            margin: 5px 10px;
            border: 1px solid #ccc;
            border-radius: 5px;
            cursor: pointer;
          }
          .active {
            padding: 0 10px;
            height: 40px;
            line-height: 40px;
            text-align: center;
            margin: 5px 10px;
            border: 2px solid #1890FF;
            border-radius: 5px;
            cursor: pointer;
          }
        }
      }
    }
  }
</style>
